import axios from 'axios';
import { getToken, clearToken } from '@/utils/auth';

const AUTH_HEADER_PREFIX = 'Bearer ';
// Token过期处理 清除本地token并跳转登录页
function handleTokenExpired() {
  clearToken();
  window.location.pathname = '/login';
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
  (config) => {
    const token: string | null = getToken();
    if (token) {
      config.headers['Authorization'] = `${AUTH_HEADER_PREFIX}${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      handleTokenExpired();
    }
    return Promise.reject(error);
  },
);
